package bruce.listener;

import cn.hutool.json.JSON;
import cn.hutool.json.JSONUtil;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.*;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;
import java.util.Arrays;

/**
 * @service
 * @description
 * @author: Bruce
 * @create: 2019-12-27
 **/
@Aspect
@Component

public class AspectConfig {
    private Logger log = LoggerFactory.getLogger(this.getClass());

    //    @Pointcut("execution(public * bruce.listener.controller.DemoController.index(..))")
//    @Pointcut("execution(* bruce.listener.controller.ControllerTest.t1(..))")
    @Pointcut("execution(* bruce.listener.controller.SonController..*(..))")
//    @Pointcut("execution(* bruce.listener.controller..*(..))")
    public void log() {
    }

    /**
     * 记录HTTP请求结束时的日志
     */
    @Before("log()")
    public void doBefore(JoinPoint joinPoint) throws Throwable {
        // 接收到请求，记录请求内容
        ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        HttpServletRequest request = attributes.getRequest();

        // 记录下请求内容
        log.info(">>>>>>>>>>Before");
        log.info("URL : " + request.getRequestURL().toString());
        log.info("HTTP_METHOD : " + request.getMethod());
        log.info("IP : " + request.getRemoteAddr());
        log.info("PATH : " + request.getServletPath());
        log.info("METHOD : " + request.getMethod());
        log.info("CLASS_METHOD : " + joinPoint.getSignature().getDeclaringTypeName() + "." + joinPoint.getSignature().getName());
        log.info("ARGS : " + Arrays.toString(joinPoint.getArgs()));
    }

    @AfterReturning(returning = "obj", pointcut = "log()")
    public void doAfterReturning(Object obj) throws Throwable {
        //处理完请求，返回内容
        log.info(">>>>>>>>>>AfterReturning");
        log.info("RESPONSE : " + JSONUtil.toJsonStr(obj));
    }

    @AfterThrowing(value = "log()", throwing = "exception")
    public void doAfterThrowing(JoinPoint joinPoint, Throwable exception) {
        //目标方法名：
        log.info(">>>>>>>>>>AfterThrowing");
        log.info(joinPoint.getSignature().getName());
        if (exception instanceof NullPointerException) {
            log.info("发生了空指针异常!!!!!");
        } else {
            log.info("发生了未知异常!!!!!");
        }
    }

    /**
     * 环绕功能强大 能在请求前后抓取数据
     */
    @Around(value = "log()")
    public Object doAroundAdvice(ProceedingJoinPoint proceedingJoinPoint) {
//        log.info(">>>>>>>>>>Around");
//        log.info("MethodName: " + proceedingJoinPoint.getSignature().getName());
        long beginTime = System.currentTimeMillis();
        try {
            Object obj = proceedingJoinPoint.proceed();
            return obj;
        } catch (Throwable throwable) {
            throwable.printStackTrace();
        } finally {
            long endTime = System.currentTimeMillis();
            log.info("BeginTime: {}, EndTime: {}, use time: {}ms", beginTime, endTime, endTime - beginTime);
        }
        return null;
    }
}
